using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;

namespace MinesweeperGame
{
    /// <summary>
    /// 排行榜条目
    /// </summary>
    public class LeaderboardEntry
    {
        public string PlayerName { get; set; }
        public int Time { get; set; }
        public DateTime Date { get; set; }

        public LeaderboardEntry(string playerName, int time)
        {
            PlayerName = playerName;
            Time = time;
            Date = DateTime.Now;
        }

        public LeaderboardEntry()
        {
            PlayerName = "";
            Time = 0;
            Date = DateTime.Now;
        }
    }

    /// <summary>
    /// 排行榜管理类
    /// </summary>
    public class Leaderboard
    {
        private Dictionary<Difficulty, List<LeaderboardEntry>> leaderboards;
        private const string LEADERBOARD_FILE = "leaderboard.json";
        private const int MAX_ENTRIES = 10;

        public Leaderboard()
        {
            leaderboards = new Dictionary<Difficulty, List<LeaderboardEntry>>();
            InitializeLeaderboards();
            LoadLeaderboard();
        }

        /// <summary>
        /// 初始化排行榜
        /// </summary>
        private void InitializeLeaderboards()
        {
            foreach (Difficulty difficulty in Enum.GetValues(typeof(Difficulty)))
            {
                leaderboards[difficulty] = new List<LeaderboardEntry>();
            }
        }

        /// <summary>
        /// 添加新成绩
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <param name="playerName">玩家姓名</param>
        /// <param name="time">完成时间（秒）</param>
        /// <returns>是否进入排行榜</returns>
        public bool AddScore(Difficulty difficulty, string playerName, int time)
        {
            if (!leaderboards.ContainsKey(difficulty))
            {
                leaderboards[difficulty] = new List<LeaderboardEntry>();
            }

            var entry = new LeaderboardEntry(playerName, time);
            var leaderboard = leaderboards[difficulty];

            // 检查是否应该进入排行榜
            if (leaderboard.Count < MAX_ENTRIES || time < leaderboard.Max(e => e.Time))
            {
                leaderboard.Add(entry);
                
                // 按时间排序（时间越短越好）
                leaderboard.Sort((a, b) => a.Time.CompareTo(b.Time));
                
                // 只保留前10名
                if (leaderboard.Count > MAX_ENTRIES)
                {
                    leaderboard.RemoveRange(MAX_ENTRIES, leaderboard.Count - MAX_ENTRIES);
                }

                SaveLeaderboard();
                return true;
            }

            return false;
        }

        /// <summary>
        /// 获取指定难度的排行榜
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <returns>排行榜列表</returns>
        public List<LeaderboardEntry> GetLeaderboard(Difficulty difficulty)
        {
            if (leaderboards.ContainsKey(difficulty))
            {
                return new List<LeaderboardEntry>(leaderboards[difficulty]);
            }
            return new List<LeaderboardEntry>();
        }

        /// <summary>
        /// 检查成绩是否应该进入排行榜
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <param name="time">完成时间（秒）</param>
        /// <returns>是否应该进入排行榜</returns>
        public bool ShouldEnterLeaderboard(Difficulty difficulty, int time)
        {
            if (!leaderboards.ContainsKey(difficulty))
            {
                return true;
            }

            var leaderboard = leaderboards[difficulty];
            return leaderboard.Count < MAX_ENTRIES || time < leaderboard.Max(e => e.Time);
        }

        /// <summary>
        /// 获取指定难度的最佳成绩
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <returns>最佳成绩，如果没有记录则返回null</returns>
        public LeaderboardEntry GetBestScore(Difficulty difficulty)
        {
            if (leaderboards.ContainsKey(difficulty) && leaderboards[difficulty].Count > 0)
            {
                return leaderboards[difficulty][0];
            }
            return null;
        }

        /// <summary>
        /// 获取指定难度的平均成绩
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <returns>平均成绩，如果没有记录则返回0</returns>
        public double GetAverageScore(Difficulty difficulty)
        {
            if (leaderboards.ContainsKey(difficulty) && leaderboards[difficulty].Count > 0)
            {
                return leaderboards[difficulty].Average(e => e.Time);
            }
            return 0;
        }

        /// <summary>
        /// 保存排行榜到文件
        /// </summary>
        private void SaveLeaderboard()
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };
                string json = JsonSerializer.Serialize(leaderboards, options);
                File.WriteAllText(LEADERBOARD_FILE, json);
            }
            catch (Exception ex)
            {
                // 保存失败时记录错误，但不影响游戏运行
                System.Diagnostics.Debug.WriteLine($"保存排行榜失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从文件加载排行榜
        /// </summary>
        private void LoadLeaderboard()
        {
            try
            {
                if (File.Exists(LEADERBOARD_FILE))
                {
                    string json = File.ReadAllText(LEADERBOARD_FILE);
                    var loadedLeaderboards = JsonSerializer.Deserialize<Dictionary<Difficulty, List<LeaderboardEntry>>>(json);
                    
                    if (loadedLeaderboards != null)
                    {
                        foreach (var kvp in loadedLeaderboards)
                        {
                            if (leaderboards.ContainsKey(kvp.Key))
                            {
                                leaderboards[kvp.Key] = kvp.Value;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 加载失败时记录错误，但不影响游戏运行
                System.Diagnostics.Debug.WriteLine($"加载排行榜失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空指定难度的排行榜
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        public void ClearLeaderboard(Difficulty difficulty)
        {
            if (leaderboards.ContainsKey(difficulty))
            {
                leaderboards[difficulty].Clear();
                SaveLeaderboard();
            }
        }

        /// <summary>
        /// 清空所有排行榜
        /// </summary>
        public void ClearAllLeaderboards()
        {
            foreach (var leaderboard in leaderboards.Values)
            {
                leaderboard.Clear();
            }
            SaveLeaderboard();
        }

        /// <summary>
        /// 获取难度级别的显示名称
        /// </summary>
        /// <param name="difficulty">难度级别</param>
        /// <returns>显示名称</returns>
        public static string GetDifficultyDisplayName(Difficulty difficulty)
        {
            switch (difficulty)
            {
                case Difficulty.Beginner:
                    return "初级";
                case Difficulty.Intermediate:
                    return "中级";
                case Difficulty.Expert:
                    return "高级";
                default:
                    return "未知";
            }
        }

        /// <summary>
        /// 格式化时间显示
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns>格式化的时间字符串</returns>
        public static string FormatTime(int seconds)
        {
            int minutes = seconds / 60;
            int remainingSeconds = seconds % 60;
            return $"{minutes:D2}:{remainingSeconds:D2}";
        }
    }
} 